<template>
  <div class="statistics-container">
    <div class="statistics-header">
      <h1>易凡科技实时监测系统</h1>
      <div class="time">{{ currentDate }}</div>
    </div>

    <el-row :gutter="10" class="statistics-layout">
      <!-- 第一行 -->
      <el-col :span="8">
        <!-- 各类新闻发布趋势 -->
        <div class="chart-box">
          <div class="chart-header">
            <h3>各类新闻发布趋势</h3>
          </div>
          <div ref="newsChartRef" class="chart-content"></div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <!-- 用户地区分布图 -->
        <div class="chart-box map-box">
          <div class="chart-header">
            <h3>用户地区分布</h3>
          </div>
          <div ref="userMapRef" class="chart-content map-chart"></div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <!-- 产品类型统计 -->
        <div class="chart-box">
          <div class="chart-header">
            <h3>产品类型统计</h3>
          </div>
          <div ref="productChartRef" class="chart-content"></div>
        </div>
      </el-col>
    </el-row>
      
    <!-- 第二行 -->
    <el-row :gutter="10" class="statistics-layout bottom-row">
      <el-col :span="8">
        <!-- 文档类型统计 -->
        <div class="chart-box">
          <div class="chart-header">
            <h3>文档类型统计</h3>
          </div>
          <div ref="docBarRef" class="chart-content"></div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <!-- 各地区统计排行 -->
        <div class="chart-box">
          <div class="chart-header">
            <h3>各地区统计排行</h3>
          </div>
          <div ref="regionChartRef" class="chart-content"></div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <!-- 招聘岗位统计 -->
        <div class="chart-box">
          <div class="chart-header">
            <h3>招聘岗位统计</h3>
          </div>
          <div ref="recruitChartRef" class="chart-content"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 图表引用
const newsChartRef = ref(null);
const userMapRef = ref(null);
const productChartRef = ref(null);
const docBarRef = ref(null);
const recruitChartRef = ref(null);
const regionChartRef = ref(null);

// 图表实例
let newsChart = null;
let userMap = null;
let productChart = null;
let docBar = null;
let recruitChart = null;
let regionChart = null;

// 当前日期
const currentDate = computed(() => {
  const date = new Date();
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
});

// 初始化各个图表
const initCharts = () => {
  // 初始化新闻分布图表
  newsChart = echarts.init(newsChartRef.value);
  
  // 初始化用户地区分布图
  userMap = echarts.init(userMapRef.value);
  
  // 初始化产品类型分析图
  productChart = echarts.init(productChartRef.value);
  
  // 初始化文档类型统计图
  docBar = echarts.init(docBarRef.value);
  
  // 初始化招聘岗位统计图
  recruitChart = echarts.init(recruitChartRef.value);
  
  // 初始化地区排行图
  regionChart = echarts.init(regionChartRef.value);
  
  // 窗口大小改变时，重绘图表
  window.addEventListener('resize', () => {
    newsChart && newsChart.resize();
    userMap && userMap.resize();
    productChart && productChart.resize();
    docBar && docBar.resize();
    recruitChart && recruitChart.resize();
    regionChart && regionChart.resize();
  });
};

// 加载所有统计数据
const loadAllStats = async () => {
  try {
    // 初始化地图数据
    try {
      await loadChineseMapData();
    } catch (err) {
      console.error('加载中国地图数据失败:', err);
    }
    
    console.log('正在获取统计数据...');
    
    // 显示加载数据的提示
    showLoading();
    
    // 单独获取各个接口数据
    try {
      // 获取用户地区分布数据
      const userLocationResponse = await axios.get('/adminapi/statistics/user-location');
      console.log('用户地区分布数据:', userLocationResponse.data);
      const userLocationStats = userLocationResponse.data.actionType === 'ok' ? userLocationResponse.data.data : [];
      
      // 获取新闻分类统计
      const newsResponse = await axios.get('/adminapi/statistics/news');
      console.log('新闻分类统计:', newsResponse.data);
      const newsStats = newsResponse.data.actionType === 'ok' ? newsResponse.data.data : [];
      
      // 获取月度新闻数据
      const monthlyNewsResponse = await axios.get('/adminapi/statistics/news/monthly');
      console.log('月度新闻数据:', monthlyNewsResponse.data);
      const monthlyNewsStats = monthlyNewsResponse.data.actionType === 'ok' ? monthlyNewsResponse.data.data : null;
      
      // 获取产品分类统计
      const boxResponse = await axios.get('/adminapi/statistics/box');
      console.log('产品分类统计:', boxResponse.data);
      const boxStats = boxResponse.data.actionType === 'ok' ? boxResponse.data.data : [];
      
      // 获取文档分类统计
      const docResponse = await axios.get('/adminapi/statistics/doc');
      console.log('文档分类统计:', docResponse.data);
      const docStats = docResponse.data.actionType === 'ok' ? docResponse.data.data : [];
      
      // 获取地区排行数据（使用用户地区数据）
      const regionStats = userLocationStats && userLocationStats.provinces ? userLocationStats.provinces : [];
      
      // 隐藏加载提示
      hideLoading();
      
      // 更新各个图表
      updateNewsChart(newsStats, monthlyNewsStats);
      updateUserMap(userLocationStats);
      updateProductChart(boxStats);
      updateDocBar(docStats);
      updateRegionChart(regionStats);
      
      // 招聘图表单独处理
      try {
        // 获取招聘数据
        const recruitResponse = await axios.get('/adminapi/statistics/recruit/radar');
        console.log('招聘雷达图数据:', recruitResponse.data);
        if (recruitResponse.data.actionType === 'ok') {
          updateRecruitChart(recruitResponse.data.data);
        } else {
          const fallbackResponse = await axios.get('/adminapi/statistics/recruit');
          console.log('招聘普通数据:', fallbackResponse.data);
          updateRecruitChart(fallbackResponse.data.actionType === 'ok' ? fallbackResponse.data.data : []);
        }
      } catch (error) {
        console.error('获取招聘数据失败:', error);
        updateRecruitChart([]);
      }
      
      console.log('所有统计数据加载完成');
    } catch (error) {
      console.error('获取统计数据失败:', error);
      // 隐藏加载提示
      hideLoading();
      // 显示空图表
      showEmptyCharts();
      
      // 显示错误信息
      ElMessage({
        message: '获取统计数据失败，已显示默认数据',
        type: 'warning',
        duration: 3000
      });
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
    // 隐藏加载提示
    hideLoading();
    // 显示空图表
    showEmptyCharts();
  }
};

// 加载中国地图数据
const loadChineseMapData = async () => {
  try {
    // 使用本地的中国地图数据文件
    const response = await axios.get('/static/map/china.json');
    // 注册地图时设置自定义配置，确保南海诸岛显示
    echarts.registerMap('china', response.data, {
      // 修改 GeoJSON 设置
      specialAreas: {
        // 南海诸岛位置设置
        南海诸岛: {
          left: 'right',
          top: 'bottom',
          width: 20,
          height: 20
        }
      }
    });
    console.log('成功加载中国地图数据，已配置南海诸岛显示');
    return true;
  } catch (err) {
    console.error('加载中国地图数据失败:', err);
    // 尝试使用备用地图数据
    try {
      // 使用简易版中国地图数据（确保有南海诸岛）
      console.log('尝试使用内置简易版中国地图数据');
      
      // 引入内置简易地图数据（如果没有，需要自行添加简易地图数据）
      // 这里使用一个非常简化的中国地图GeoJSON，确保包含南海诸岛
      const simpleMapData = {
        "type": "FeatureCollection",
        "features": [
          // 简化的中国大陆轮廓
          {
            "type": "Feature",
            "properties": { "name": "中国大陆" },
            "geometry": {
              "type": "Polygon",
              "coordinates": [[[73, 18], [135, 18], [135, 54], [73, 54], [73, 18]]]
            }
          },
          // 南海诸岛
          {
            "type": "Feature",
            "properties": { "name": "南海诸岛" },
            "geometry": {
              "type": "Polygon",
              "coordinates": [[[109, 4], [117, 4], [117, 12], [109, 12], [109, 4]]]
            }
          }
        ]
      };
      
      // 注册简易地图
      echarts.registerMap('china', simpleMapData, {
        specialAreas: {
          南海诸岛: {
            left: 'right',
            top: 'bottom',
            width: 20,
            height: 20
          }
        }
      });
      
      console.log('成功注册内置简易地图');
      return true;
    } catch (e) {
      console.error('注册内置中国地图数据失败:', e);
      return false;
    }
  }
};

// 显示图表加载状态
const showLoading = () => {
  const options = {
    text: '加载数据中...',
    color: '#36CBCB',
    textColor: '#fff',
    maskColor: 'rgba(0, 0, 0, 0.5)',
    zlevel: 0
  };
  
  newsChart && newsChart.showLoading(options);
  userMap && userMap.showLoading(options);
  productChart && productChart.showLoading(options);
  docBar && docBar.showLoading(options);
  recruitChart && recruitChart.showLoading(options);
  regionChart && regionChart.showLoading(options);
};

// 隐藏图表加载状态
const hideLoading = () => {
  newsChart && newsChart.hideLoading();
  userMap && userMap.hideLoading();
  productChart && productChart.hideLoading();
  docBar && docBar.hideLoading();
  recruitChart && recruitChart.hideLoading();
  regionChart && regionChart.hideLoading();
};

// 显示空图表
const showEmptyCharts = () => {
  const emptyNewsData = [
    { name: "最新动态", value: 0 },
    { name: "典型案例", value: 0 },
    { name: "行业新闻", value: 0 }
  ];
  
  const emptyBoxData = [
    { name: "信息科技", value: 0 },
    { name: "智能家居", value: 0 },
    { name: "物联网产品", value: 0 }
  ];
  
  const emptyDocData = [
    { name: "A级文档", value: 0 },
    { name: "B级文档", value: 0 },
    { name: "C级文档", value: 0 }
  ];
  
  const emptyRecruitData = [
    { name: "技术岗位", value: 0 },
    { name: "产品岗位", value: 0 },
    { name: "市场岗位", value: 0 },
    { name: "运营岗位", value: 0 },
    { name: "设计岗位", value: 0 }
  ];
  
  updateNewsChart(emptyNewsData, null);
  updateUserMap([]);
  updateProductChart(emptyBoxData);
  updateDocBar(emptyDocData);
  updateRecruitChart(emptyRecruitData);
  updateRegionChart([]);
};

// 更新新闻趋势图(堆叠面积图)
const updateNewsChart = (data, monthlyData) => {
  if (!newsChart) return;
  
  // 月份名称
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  
  console.log('新闻总数据:', data);
  console.log('新闻月度数据:', monthlyData);
  
  // 准备图表数据
  let seriesData;
  
  if (monthlyData && Array.isArray(monthlyData) && monthlyData.length > 0) {
    // 使用后端返回的月度数据
    console.log('使用月度数据生成图表...');
    seriesData = monthlyData.map(item => {
      console.log(`${item.name} 月度数据:`, item.values);
      return {
        name: item.name,
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: item.values || new Array(12).fill(0)
      };
    });
  } else {
    // 使用总数据创建系列数据
    console.log('使用总数据平均分配到月份...');
    
    // 确保data是数组并且有值
    const validData = Array.isArray(data) && data.length > 0 ? data : [
      { name: "最新动态", value: 0 },
      { name: "典型案例", value: 0 },
      { name: "行业新闻", value: 0 }
    ];
    
    seriesData = validData.map(item => ({
      name: item.name,
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      // 每个月的数据平均分配，确保有值
      data: new Array(12).fill(Math.max(0, Math.floor((item.value || 0) / 12)))
    }));
  }
  
  console.log('最终图表数据:', seriesData);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: seriesData.map(item => item.name),
      top: '5%',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: monthNames,
        axisLabel: {
          color: '#fff'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: '#fff'
        }
      }
    ],
    series: seriesData
  };

  newsChart.setOption(option);
};

// 更新用户地区分布图
const updateUserMap = (data) => {
  if (!userMap) return;
  
  // 检查数据格式，适配新旧数据结构
  let mapData = [];
  let cityData = {};
  
  if (Array.isArray(data)) {
    // 旧格式，直接使用数组
    console.log('用户地区分布数据(旧格式):', data);
    mapData = data.map(item => ({
      name: item.name,
      value: item.value
    }));
  } else if (data && data.provinces) {
    // 新格式，使用provinces、cities
    console.log('用户地区分布数据(新格式):', data);
    mapData = data.provinces;
    cityData = data.cities || {};
  }
  
  try {
    // 计算最大值，避免所有值为0时出错
    const maxValue = Math.max(...mapData.map(item => item.value || 0), 1);
    
    // 如果没有真实地区数据，使用模拟数据
    if (mapData.length === 0) {
      console.log('未获取到地区分布数据，使用模拟数据');
      
      // 生成随机的省级数据
      const provinces = [
        '北京', '上海', '广东', '浙江', '江苏', '山东', 
        '四川', '重庆', '陕西', '湖北', '湖南', '河南', '天津'
      ];
      
      mapData = provinces.map(province => ({
        name: province,
        value: Math.floor(Math.random() * 100) + 50 // 50-150人随机
      }));
      
      // 生成城市分布数据
      cityData = {};
      provinces.forEach(province => {
        // 为每个省份添加2-4个城市
        const citiesCount = Math.floor(Math.random() * 3) + 2;
        cityData[province] = [];
        
        for (let i = 0; i < citiesCount; i++) {
          // 根据省份选择合适的城市名
          let cityName = '';
          if (province === '北京') cityName = ['朝阳区', '海淀区', '西城区'][i % 3];
          else if (province === '上海') cityName = ['浦东新区', '静安区', '徐汇区'][i % 3];
          else if (province === '广东') cityName = ['广州', '深圳', '东莞', '珠海'][i % 4];
          else if (province === '浙江') cityName = ['杭州', '宁波', '温州', '嘉兴'][i % 4];
          else if (province === '天津') cityName = ['和平区', '河西区', '南开区'][i % 3];
          else cityName = `${province}城市${i+1}`;
          
          cityData[province].push({
            name: cityName,
            value: Math.floor(Math.random() * 20) + 5 // 5-25人随机
          });
        }
      });
    }
    
    // 设置地图配置
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          const name = params.name;
          const value = params.value || 0;
          if (name === '南海诸岛') {
            return `南海诸岛: ${value}人`;
          }
          return `${name}: ${value}人`;
        },
        confine: true
      },
      visualMap: {
        min: 0,
        max: maxValue,
        text: ['高', '低'],
        realtime: false,
        calculable: true,
        inRange: {
          color: ['#e0f3f8', '#045fb4']
        },
        textStyle: {
          color: '#fff'
        }
      },
      series: [
        {
          name: '用户分布',
          type: 'map',
          map: 'china',
          zoom: 1.2,
          aspectScale: 0.75,
          layoutCenter: ['50%', '50%'],
          layoutSize: '100%',
          mapLocation: {
            x: 'center',
            y: 'center'
          },
          label: {
            show: true,
            color: '#fff',
            fontSize: 8
          },
          itemStyle: {
            areaColor: '#142957',
            borderColor: '#0bc1f2',
            borderWidth: 1
          },
          emphasis: {
            label: {
              color: '#fff',
              fontSize: 10,
              fontWeight: 'bold'
            },
            itemStyle: {
              areaColor: '#0a7dbe'
            }
          },
          // 显示南海诸岛
          showLegendSymbol: true,
          roam: true,
          selectedMode: false,
          layouts: [{
            type: 'islands', // 显示南海诸岛
            left: 'right',
            top: 'bottom',
            size: '20%'
          }],
          // 确保南海诸岛区域颜色
          regions: [{
            name: '南海诸岛',
            itemStyle: {
              areaColor: '#142957',
              borderColor: '#0bc1f2',
              normal: {
                opacity: 1,
                label: {
                  show: true,
                  color: '#fff',
                  fontSize: 10
                }
              }
            },
            label: {
              show: true,
              color: '#fff',
              fontSize: 10,
              formatter: (params) => {
                // 显示南海诸岛用户数量
                const item = mapData.find(d => d.name === '南海诸岛');
                const value = item ? item.value : 0;
                return `南海诸岛: ${value}人`;
              }
            },
            emphasis: {
              label: {
                show: true,
                color: '#fff',
                fontSize: 12,
                fontWeight: 'bold'
              }
            }
          }],
          data: mapData
        }
      ]
    };
    
    // 添加用户角色闪光点
    // 设置管理员和编辑角色的位置数据
    let adminLocations = [];
    let editorLocations = [];
    
    // 使用后端返回的角色位置数据
    if (data && data.adminLocations && data.adminLocations.length > 0) {
      adminLocations = data.adminLocations.map(item => ({
        name: item.name,
        value: item.value,
        coords: item.coords
      }));
    } else {
      // 默认管理员位置数据
      adminLocations = [
        {name: '北京', value: 9, coords: [116.405285, 39.904989]},
        {name: '成都', value: 5, coords: [104.065735, 30.659462]},
        {name: '太原', value: 3, coords: [112.549248, 37.857014]},
        {name: '镇江', value: 2, coords: [119.452753, 32.204402]}
      ];
    }
    
    if (data && data.editorLocations && data.editorLocations.length > 0) {
      editorLocations = data.editorLocations.map(item => ({
        name: item.name,
        value: item.value,
        coords: item.coords
      }));
    } else {
      // 默认编辑位置数据
      editorLocations = [
        {name: '上海', value: 8, coords: [121.472644, 31.231706]},
        {name: '广州', value: 6, coords: [113.280637, 23.125178]},
        {name: '南宁', value: 4, coords: [108.320004, 22.82402]},
        {name: '哈尔滨', value: 3, coords: [126.642464, 45.756967]},
        {name: '深圳', value: 7, coords: [114.085947, 22.547]},
        {name: '杭州', value: 5, coords: [120.153576, 30.287459]},
        {name: '西安', value: 4, coords: [108.948024, 34.263161]},
        {name: '重庆', value: 6, coords: [106.504962, 29.533155]}
      ];
    }

    // 添加管理员闪光点(青色)
    option.series.push({
      name: '管理员',
      type: 'effectScatter',
      coordinateSystem: 'geo',
      data: adminLocations.map(item => ({
        name: item.name,
        value: [...item.coords, item.value],
        progress: 1  // 添加progress属性，解决错误
      })),
      symbolSize: function (val) {
        return Math.min(val[2] * 1.5, 15);
      },
      showEffectOn: 'render',
      rippleEffect: {
        brushType: 'stroke',
        scale: 4,
        period: 4
      },
      label: {
        formatter: '{b}',
        position: 'right',
        show: false
      },
      emphasis: {
        label: {
          show: true
        }
      },
      itemStyle: {
        color: '#0bc1f2'
      },
      tooltip: {
        formatter: function(params) {
          return `${params.name}: ${params.value[2]}位管理员`;
        }
      }
    });

    // 添加编辑人员闪光点(蓝色)
    option.series.push({
      name: '编辑人员',
      type: 'effectScatter',
      coordinateSystem: 'geo',
      data: editorLocations.map(item => ({
        name: item.name,
        value: [...item.coords, item.value],
        progress: 1  // 添加progress属性，解决错误
      })),
      symbolSize: function (val) {
        return Math.min(val[2] * 1.2, 12);
      },
      showEffectOn: 'render',
      rippleEffect: {
        brushType: 'stroke',
        scale: 3,
        period: 5
      },
      label: {
        formatter: '{b}',
        position: 'right',
        show: false
      },
      emphasis: {
        label: {
          show: true
        }
      },
      itemStyle: {
        color: '#3a6ff2'
      },
      tooltip: {
        formatter: function(params) {
          return `${params.name}: ${params.value[2]}位编辑人员`;
        }
      }
    });

    userMap.setOption(option);
    console.log('用户地区分布图表已更新');
  } catch (error) {
    console.error('用户地区分布图表渲染失败:', error);
    
    // 渲染失败时，使用柱状图作为备选
    const barOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: mapData.slice(0, 10).map(item => item.name),
        axisLabel: {
          color: '#fff'
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#fff'
        }
      },
      series: [{
        name: '用户数量',
        type: 'bar',
        data: mapData.slice(0, 10).map(item => item.value),
        itemStyle: {
          color: '#409EFF'
        }
      }]
    };
    
    userMap.setOption(barOption);
    console.log('已切换到备选柱状图显示');
  }
};

// 更新产品类型分析图
const updateProductChart = (data) => {
  if (!productChart) return;
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: '15%',
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '产品类型',
        type: 'pie',
        radius: '50%',
        center: ['40%', '50%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          color: '#fff'
        }
      }
    ]
  };
  
  productChart.setOption(option);
};

// 更新文档类型统计图
const updateDocBar = (data) => {
  if (!docBar) return;
  
  // 排序数据，从高到低
  const sortedData = [...data].sort((a, b) => b.value - a.value);
  
  // 获取类别和值
  const categories = sortedData.map(item => item.name);
  const values = sortedData.map(item => item.value);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      confine: true
    },
    grid: {
      top: '5%',
      left: '3%',
      right: '12%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        color: '#fff',
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: categories.length > 0 ? categories : ['A级文档', 'B级文档', 'C级文档'],
      axisLabel: {
        color: '#fff',
        fontSize: 12
      },
      axisTick: {
        alignWithLabel: true
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      }
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: values.length > 0 ? values : [1, 1, 0],
        barWidth: '60%',
        itemStyle: {
          normal: {
            color: function(params) {
              // 添加渐变色效果
              const colorList = [
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {offset: 0, color: '#6c7bd8'},
                  {offset: 1, color: '#9d98fa'}
                ]),
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {offset: 0, color: '#6c7bd8'},
                  {offset: 1, color: '#9d98fa'}
                ])
              ];
              return colorList[params.dataIndex % colorList.length];
            },
            borderRadius: [0, 4, 4, 0]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}',
          color: '#fff',
          fontSize: 12,
          distance: 5
        }
      }
    ]
  };
  
  docBar.setOption(option);
};

// 更新招聘岗位图(雷达图)
const updateRecruitChart = async (data) => {
  if (!recruitChart) return;
  
  try {
    // 如果传入的数据是雷达图格式
    if (data && data.categories && data.series) {
      const radarData = data;
      
      // 配置雷达图
      const option = {
        color: ['#5470c6', '#91cc75'],
        tooltip: {
          trigger: 'item',
          confine: true
        },
        legend: {
          data: ['招聘预算', '实际招聘'],
          orient: 'vertical',
          right: '1%',
          top: '15%',
          textStyle: {
            color: '#fff'
          }
        },
        radar: {
          indicator: radarData.categories.map(category => {
            return {
              name: category,
              max: Math.max(...radarData.series.map(s => Math.max(...s.value))) + 2
            };
          }),
          radius: '60%',
          center: ['45%', '55%'],
          splitNumber: 4,
          axisName: {
            color: '#fff',
            fontSize: 12
          },
          splitArea: {
            areaStyle: {
              color: ['rgba(255, 255, 255, 0.05)', 'rgba(255, 255, 255, 0.1)']
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          }
        },
        series: [{
          name: '招聘统计',
          type: 'radar',
          data: radarData.series.map(item => {
            return {
              value: item.value,
              name: item.name,
              symbolSize: 6,
              lineStyle: {
                width: 2
              },
              areaStyle: {
                opacity: 0.2
              }
            };
          })
        }]
      };
      
      recruitChart.setOption(option);
      return;
    }
    
    // 如果数据是普通数组格式，显示为柱状图
    if (Array.isArray(data) && data.length > 0) {
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: '15%',
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '岗位分布',
            type: 'pie',
            radius: '60%',
            center: ['40%', '55%'],
            data: data,
            label: {
              color: '#fff',
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      recruitChart.setOption(option);
      return;
    }
    
    // 使用默认数据
    const defaultOption = {
      color: ['#5470c6', '#91cc75'],
      tooltip: {
        trigger: 'item'
      },
      legend: {
        data: ['招聘预算', '实际招聘'],
        orient: 'vertical',
        right: '5%',
        top: '15%',
        textStyle: {
          color: '#fff'
        }
      },
      radar: {
        indicator: [
          { name: '技术岗位', max: 10 },
          { name: '产品岗位', max: 10 },
          { name: '市场岗位', max: 10 },
          { name: '运营岗位', max: 10 },
          { name: '设计岗位', max: 10 },
          { name: '行政岗位', max: 10 }
        ],
        radius: '60%',
        center: ['45%', '55%'],
        splitNumber: 4,
        axisName: {
          color: '#fff',
          fontSize: 12
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(255, 255, 255, 0.05)', 'rgba(255, 255, 255, 0.1)']
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      series: [{
        name: '招聘统计',
        type: 'radar',
        data: [
          {
            value: [8, 5, 6, 4, 3, 2],
            name: '招聘预算',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.2
            }
          },
          {
            value: [5, 4, 3, 4, 5, 1],
            name: '实际招聘',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.2
            }
          }
        ]
      }]
    };
    
    recruitChart.setOption(defaultOption);
  } catch (error) {
    console.error('更新招聘雷达图数据失败:', error);
    
    // 出错时使用默认数据
    const fallbackOption = {
      color: ['#5470c6', '#91cc75'],
      tooltip: {
        trigger: 'item'
      },
      legend: {
        data: ['招聘预算', '实际招聘'],
        orient: 'vertical',
        right: '5%',
        top: '15%',
        textStyle: {
          color: '#fff'
        }
      },
      radar: {
        indicator: [
          { name: '技术岗位', max: 10 },
          { name: '产品岗位', max: 10 },
          { name: '市场岗位', max: 10 },
          { name: '运营岗位', max: 10 },
          { name: '设计岗位', max: 10 },
          { name: '行政岗位', max: 10 }
        ],
        radius: '60%',
        center: ['45%', '55%'],
        splitNumber: 4,
        axisName: {
          color: '#fff',
          fontSize: 12
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(255, 255, 255, 0.05)', 'rgba(255, 255, 255, 0.1)']
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      series: [{
        name: '招聘统计',
        type: 'radar',
        data: [
          {
            value: [8, 5, 6, 4, 3, 2],
            name: '招聘预算',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.2
            }
          },
          {
            value: [5, 4, 3, 4, 5, 1],
            name: '实际招聘',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.2
            }
          }
        ]
      }]
    };
    
    recruitChart.setOption(fallbackOption);
  }
};

// 更新地区排行榜
const updateRegionChart = (data) => {
  if (!regionChart) return;
  
  try {
    // 对地区数据进行排序，取前10个
    const sortedData = Array.isArray(data) ? [...data].sort((a, b) => b.value - a.value).slice(0, 10) : [];
    const locations = sortedData.map(item => item.name);
    const values = sortedData.map(item => item.value);
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        confine: true,
        formatter: '{b}: {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '5%',
        top: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: locations.length > 0 ? locations : ['浙江', '重庆', '四川', '河北', '山东', '陕西', '吉林', '湖南', '山西', '湖北'],
        axisLabel: {
          color: '#fff',
          interval: 0,
          rotate: 45,
          fontSize: 10
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#fff',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '用户数量',
          type: 'bar',
          barWidth: '50%',
          data: values.length > 0 ? values : [194, 185, 178, 170, 151, 138, 132, 128, 121, 106],
          itemStyle: {
            normal: {
              color: function(params) {
                // 创建渐变色
                const colorList = [
                  new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#57eeff'},
                    {offset: 1, color: '#0c6cf1'}
                  ]),
                  new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#7b8af9'},
                    {offset: 1, color: '#4e4cbe'}
                  ])
                ];
                return colorList[params.dataIndex % 2];
              },
              borderRadius: [4, 4, 0, 0]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
            color: '#fff',
            fontSize: 10,
            distance: 5
          }
        }
      ]
    };
    
    regionChart.setOption(option);
  } catch (error) {
    console.error('更新地区排行榜失败:', error);
    
    // 使用默认数据
    const defaultOption = {
      tooltip: {
        trigger: 'axis',
        confine: true
      },
      grid: {
        left: '3%',
        right: '5%',
        bottom: '5%',
        top: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['浙江', '重庆', '四川', '河北', '山东', '陕西', '吉林', '湖南', '山西', '湖北'],
        axisLabel: {
          color: '#fff',
          rotate: 45,
          fontSize: 10
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#fff',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '用户数量',
          type: 'bar',
          barWidth: '50%',
          data: [194, 185, 178, 170, 151, 138, 132, 128, 121, 106],
          itemStyle: {
            normal: {
              color: function(params) {
                // 创建渐变色
                const colorList = [
                  new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#57eeff'},
                    {offset: 1, color: '#0c6cf1'}
                  ]),
                  new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#7b8af9'},
                    {offset: 1, color: '#4e4cbe'}
                  ])
                ];
                return colorList[params.dataIndex % 2];
              },
              borderRadius: [4, 4, 0, 0]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
            color: '#fff',
            fontSize: 10,
            distance: 5
          }
        }
      ]
    };
    
    regionChart.setOption(defaultOption);
  }
};

onMounted(async () => {
  // 等待DOM渲染完成
  await nextTick();
  
  // 初始化图表
  initCharts();
  
  // 添加错误处理逻辑
  try {
    // 加载统计数据
    await loadAllStats();
  } catch (error) {
    console.error('加载统计数据失败:', error);
    // 显示空图表
    showEmptyCharts();
    
    // 显示错误提示
    ElMessage({
      message: '加载统计数据失败，已显示默认数据',
      type: 'warning',
      duration: 3000
    });
  }
  
  // 当窗口大小改变时，重新调整图表大小
  window.addEventListener('resize', () => {
    if (newsChart) newsChart.resize();
    if (userMap) userMap.resize();
    if (productChart) productChart.resize();
    if (docBar) docBar.resize();
    if (recruitChart) recruitChart.resize();
    if (regionChart) regionChart.resize();
  });
});

// 组件销毁时清理
onUnmounted(() => {
  // 清理图表实例
  if (newsChart) newsChart.dispose();
  if (userMap) userMap.dispose();
  if (productChart) productChart.dispose();
  if (docBar) docBar.dispose();
  if (recruitChart) recruitChart.dispose();
  if (regionChart) regionChart.dispose();
  
  // 移除事件监听
  window.removeEventListener('resize', () => {});
});
</script>

<style lang="scss" scoped>
.statistics-container {
  width: 100%;
  height: 100%;
  background-color: #14161f;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  margin: 0;
  background-color: #14161f;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  height: 42px; /* 固定高度 */
  
  h1 {
    margin: 0;
    font-size: 22px;
    font-weight: bold;
    background: linear-gradient(45deg, #36CBCB, #5470c6);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  
  .time {
    font-size: 16px;
    color: #36CBCB;
  }
}

.statistics-layout {
  padding: 5px;
  height: calc((100% - 42px) / 2); /* 计算每行高度，减去头部高度后平分 */
  
  &.bottom-row {
    margin-top: 0;
    margin-bottom: 0;
  }
  
  .el-col {
    height: 100%;
  }
}

.chart-box {
  height: 100%;
  background-color: #1b1f28;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  border: 1px solid rgba(54, 203, 203, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(54, 203, 203, 0.2);
    border-color: rgba(54, 203, 203, 0.3);
  }
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    position: relative;
    z-index: 2;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: normal;
      position: relative;
      padding-left: 10px;
      
      &:before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #36CBCB;
        border-radius: 2px;
      }
    }
  }
  
  .chart-content {
    flex: 1;
    width: 100%;
    position: relative;
    z-index: 1;
  }
  
  &:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(to right, #36CBCB, transparent);
  }
  
  &:after {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 2px;
    background: linear-gradient(to bottom, #36CBCB, transparent);
  }
}

.map-chart {
  height: 100%;
}

@media screen and (max-width: 1200px) {
  .statistics-container {
    height: auto;
    overflow: auto;
  }
  
  .statistics-layout {
    height: auto;
    min-height: 350px;
    margin-bottom: 10px;
    
    .el-col {
      height: 350px;
      margin-bottom: 10px;
    }
    
    &.bottom-row {
      min-height: 350px;
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
  
  .chart-box {
    height: 350px;
    margin-bottom: 10px;
  }
  
  .map-chart {
    height: 350px;
  }
}

@media screen and (min-width: 1201px) and (max-height: 900px) {
  .statistics-layout {
    .el-col {
      .chart-box {
        .chart-header {
          margin-bottom: 2px;
        }
      }
    }
  }
}

@media screen and (min-width: 1201px) {
  .chart-box {
    margin-bottom: 0;
  }
}
</style>
